from datetime import datetime, timedelta
import os


def get_next_day(date_,h=2):
    # 获取当前日期和时间
    current_date_time = datetime.strptime(date_, "%Y%m%d")

    # 计算下一天的日期
    next_day = current_date_time + timedelta(days=1)
    noon = datetime.strptime(f"0{h}:00", "%H:%M").time()  #
    next_day = datetime.combine(next_day.date(), noon) - timedelta(minutes=1)
    # 返回下一天的日期
    return next_day



def normalize_datetime(dt):
    # 如果时间在0-2小时内，将日期减去一天
    if dt.hour < 2:
        dt -= timedelta(days=1)

    # 格式化日期为 "%Y%m%d" 格式并返回
    formatted_date = dt.strftime("%Y%m%d")
    return formatted_date



def get_cur_processed_path(location):
	# 检查输入的 location 是否符合预期格式
	if not location:
		return ""
	if location.startswith("kmnode") and len(location) >= 7:
		# 提取数字部分
		node_number = location[6:8]  # 假设数字部分是两位
		# 检查数字部分是否有效
		if node_number.isdigit():
			# 构造返回的 IP 地址和端口号
			
			port =int(node_number)
			return f"/all/data_products/kmnode{port:02}/1m6"
		else:
			# 如果数字部分无效，返回 None 或抛出异常
			return None
	else:
		# 如果 location 格式不符合预期，返回 None 或抛出异常
		return None

def build_fits_path(rec, version):
    """
    构造单条记录的 CalMag 星表路径。
    """
    try:
        formatted_date = normalize_datetime(rec['obs_date'])
        root_reception = get_cur_processed_path(rec['location'])

        # 组路径：/.../reception/V2025xxxx/yyyyMMdd/sci/[xx]_object_filter/YYYYMMDDTHHMMSS/
        subdir = "{prefix}_{object}_{filter}".format(
            prefix=rec['filename'][:2],
            object=rec['object'],
            filter=rec['filter']
        )
        timestamp = str(rec['obs_date']).replace('-', '').replace(':', '').replace(' ', 'T')

        full_path = os.path.join(
            root_reception,
            "reception", version,
            formatted_date, "sci", subdir,
            timestamp,
            rec['filename'].replace(".fits", "_sciimg_sexcat_CalMag_AperCorr.fits")
        )

        return full_path
    except Exception as e:
        print(f"[WARN] 构造路径失败: {e}，rec = {rec}")
        return None